<template>
  <div class="content-categories">
    <el-card class="page-header">
      <template #header>
        <div class="header-title">
          <h2>内容分类管理</h2>
          <el-button type="primary" @click="handleAddCategory">添加分类</el-button>
        </div>
      </template>
    </el-card>

    <!-- 分类表格 -->
    <el-card class="category-table-card">
      <el-table
        v-loading="loading"
        :data="categoryList"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="分类名称" min-width="200" />
        <el-table-column prop="id" label="分类ID" min-width="100" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="启用状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="scope">
            <el-button 
              size="small" 
              @click="handleAddSubCategory(scope.row)"
              >添加子分类</el-button
            >
            <el-button 
              size="small" 
              type="primary" 
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑分类弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑分类' : (isAddSub ? '添加子分类' : '添加分类')"
      width="500px"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item v-if="isAddSub" label="父级分类">
          <el-input v-model="categoryForm.parentName" disabled />
        </el-form-item>
        <el-form-item v-else-if="!isEdit" label="父级分类">
          <el-cascader
            v-model="categoryForm.parentId"
            :options="categoryOptions"
            :props="{ 
              checkStrictly: true,
              value: 'id',
              label: 'name'
            }"
            clearable
            placeholder="请选择父级分类(可选)"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="categoryForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-switch 
            v-model="categoryForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 列表数据
const loading = ref(false)
const categoryList = ref([])

// 模拟数据
const mockCategories = [
  {
    id: '1',
    name: '健康知识',
    sort: 1,
    status: 1,
    createTime: '2023-01-10 10:30:22',
    children: [
      {
        id: '1-1',
        name: '饮食健康',
        sort: 1,
        status: 1,
        createTime: '2023-01-11 09:15:36'
      },
      {
        id: '1-2',
        name: '运动健身',
        sort: 2,
        status: 1,
        createTime: '2023-01-12 14:25:18'
      }
    ]
  },
  {
    id: '2',
    name: '医疗资讯',
    sort: 2,
    status: 1,
    createTime: '2023-01-15 11:40:55',
    children: [
      {
        id: '2-1',
        name: '名医访谈',
        sort: 1,
        status: 1,
        createTime: '2023-01-16 16:20:42'
      },
      {
        id: '2-2',
        name: '医疗政策',
        sort: 2,
        status: 0,
        createTime: '2023-01-17 09:50:31'
      }
    ]
  },
  {
    id: '3',
    name: '生活方式',
    sort: 3,
    status: 1,
    createTime: '2023-01-20 13:45:28'
  }
]

// 弹窗相关
const dialogVisible = ref(false)
const categoryFormRef = ref(null)
const isEdit = ref(false)
const isAddSub = ref(false)
const categoryForm = reactive({
  id: '',
  name: '',
  parentId: '',
  parentName: '',
  sort: 0,
  status: 1
})
const categoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
}

// 获取分类列表
const getCategoryList = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    categoryList.value = mockCategories
    loading.value = false
  }, 500)
}

// 计算级联选择器的选项
const categoryOptions = computed(() => {
  // 深拷贝防止修改原数据
  return JSON.parse(JSON.stringify(categoryList.value))
})

// 添加分类
const handleAddCategory = () => {
  resetForm()
  isEdit.value = false
  isAddSub.value = false
  dialogVisible.value = true
}

// 添加子分类
const handleAddSubCategory = (row) => {
  resetForm()
  isEdit.value = false
  isAddSub.value = true
  categoryForm.parentId = row.id
  categoryForm.parentName = row.name
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row) => {
  resetForm()
  isEdit.value = true
  isAddSub.value = false
  Object.assign(categoryForm, row)
  dialogVisible.value = true
}

// 删除分类
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除分类"${row.name}"吗？删除后将无法恢复!`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟删除操作
    ElMessage.success('删除成功')
    // 重新获取数据
    getCategoryList()
  }).catch(() => {
    // 取消删除
  })
}

// 更改状态
const handleStatusChange = (row) => {
  const statusText = row.status === 1 ? '启用' : '禁用'
  ElMessage.success(`已${statusText}分类：${row.name}`)
}

// 重置表单
const resetForm = () => {
  if (categoryFormRef.value) {
    categoryFormRef.value.resetFields()
  }
  Object.assign(categoryForm, {
    id: '',
    name: '',
    parentId: '',
    parentName: '',
    sort: 0,
    status: 1
  })
}

// 取消表单
const cancelForm = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const submitForm = () => {
  categoryFormRef.value?.validate((valid) => {
    if (valid) {
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
        dialogVisible.value = false
        // 重新获取数据
        getCategoryList()
      }, 300)
    }
  })
}

onMounted(() => {
  getCategoryList()
})
</script>

<style scoped>
.content-categories {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title h2 {
  margin: 0;
  font-size: 20px;
}

.category-table-card {
  margin-bottom: 20px;
}
</style> 